package org.clzps.filetransfer.http;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.clzps.filetransfer.FileTransferHelper;
import org.clzps.filetransfer.common.SynchroCommon;

/**
 * Http上传文件的辅助工具类
 * @author Aries Chou 13/09/2011
 */
public class HttpTransferHelper extends FileTransferHelper{
	/**
	 * Http形式上传单个文件，只处理<input type="file" ... />的项，调用如：<br />
	 * &nbsp;&nbsp;uploadFile(request, "E:\\testProject\\webapp\\upload\\")
	 * @param request				HttpServletRequest对象
	 * @param uploadPath			上传至uploadPath目录
	 * @throws ServletException		抛出ServletException异常
	 * @throws IOException			抛出IOException异常
	 * @return	上传成功则返回上传文件的HttpFileInfo对象，否则返回null;
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public HttpFileInfo uploadFile(HttpServletRequest request, String uploadPath) throws ServletException, IOException{
		HttpFileInfo httpFileInfo = null;
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		
		if(!isMultipart) {
			throw new RuntimeException();
		}
		
		//Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(1024 * 1024 * 4);
		CustomServletFileUpload upload = new CustomServletFileUpload(factory);
		
		logger.info("Http File Uploading...");
		try {
			List items = upload.parseRequest(request);
			
			Iterator iter = items.iterator();
			
			while(iter.hasNext()) {
				FileItem item = (FileItem)iter.next();
				Long size = item.getSize();
				String fileName = item.getName();
				fileName =  fileName.substring(fileName.lastIndexOf("\\") + 1);
				String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
				String storeFileName = SynchroCommon.getFileName(suffix);
				
				File file = new File(uploadPath + storeFileName);
				item.write(file);
				
				logger.info("Http File Uploaded.");
				
				httpFileInfo = new HttpFileInfo();
				DecimalFormat formatter = new DecimalFormat("0.00");
				double tmpSize = size / 1024.0;
				if(tmpSize > 1024) {
					tmpSize = tmpSize / 1024.0;
					httpFileInfo.setUnit("MB");
				} else {
					httpFileInfo.setUnit("KB");
				}
				httpFileInfo.setStoreFileName(storeFileName);
				httpFileInfo.setFileName(fileName);
				httpFileInfo.setSize(Float.parseFloat(formatter.format(tmpSize)));
			}
		} catch(FileUploadException e) {
			e.printStackTrace();
			logger.error("parseRequest Error");
		} catch(Exception e) {
			e.printStackTrace();
			logger.error("write File Error");
		}
		
		return httpFileInfo;
	}
}
